package com.eastmelon.javase;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheDemo {
	private Map<String, Object> cache = new HashMap<String, Object>();

	public static void main(String[] args) {

	}

	private ReadWriteLock rw = new ReentrantReadWriteLock();

	public Object getData(String key) {
		rw.readLock().lock();
		Object value = null;
		try {
			value = cache.get("key");
			if (value == null) {
				rw.readLock().unlock();
				rw.writeLock().lock();
				try {
					if (value == null) {//防止后面的线程也进行写操作
						value = "aaa";// 进行数据库操作，并存入缓存
					}
				}
				finally {
					rw.writeLock().unlock();
				}
			}
		}
		finally {
			rw.readLock().lock();
		}
		return value;
	}
}
